<template>
  <div class="settings-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">设置</h1>
        <p class="page-subtitle">管理你的账户和偏好设置</p>
      </div>
      
      <div class="settings-container">
        <div class="settings-nav">
          <button 
            v-for="tab in tabs" 
            :key="tab.id"
            :class="['nav-item', { active: activeTab === tab.id }]"
            @click="activeTab = tab.id"
          >
            <span class="nav-icon">{{ tab.icon }}</span>
            {{ tab.name }}
          </button>
        </div>
        
        <div class="settings-content">
          <!-- 账户设置 -->
          <div v-if="activeTab === 'account'" class="settings-section">
            <h2 class="section-title">账户设置</h2>
            
            <div class="setting-group">
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">用户名</h3>
                  <p class="setting-desc">你的显示名称</p>
                </div>
                <div class="setting-control">
                  <input 
                    v-model="accountSettings.username" 
                    type="text" 
                    class="setting-input"
                    @blur="saveAccountSettings"
                  />
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">邮箱</h3>
                  <p class="setting-desc">用于接收通知和找回密码</p>
                </div>
                <div class="setting-control">
                  <input 
                    v-model="accountSettings.email" 
                    type="email" 
                    class="setting-input"
                    @blur="saveAccountSettings"
                  />
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">修改密码</h3>
                  <p class="setting-desc">定期更新密码以保护账户安全</p>
                </div>
                <div class="setting-control">
                  <button class="btn btn-secondary" @click="showPasswordModal = true">
                    修改密码
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 通知设置 -->
          <div v-if="activeTab === 'notifications'" class="settings-section">
            <h2 class="section-title">通知设置</h2>
            
            <div class="setting-group">
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">邮件通知</h3>
                  <p class="setting-desc">接收重要更新和活动通知</p>
                </div>
                <div class="setting-control">
                  <label class="toggle">
                    <input 
                      v-model="notificationSettings.email" 
                      type="checkbox"
                      @change="saveNotificationSettings"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">推送通知</h3>
                  <p class="setting-desc">接收实时消息和提醒</p>
                </div>
                <div class="setting-control">
                  <label class="toggle">
                    <input 
                      v-model="notificationSettings.push" 
                      type="checkbox"
                      @change="saveNotificationSettings"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">角色更新通知</h3>
                  <p class="setting-desc">当你的角色被评论或使用时通知</p>
                </div>
                <div class="setting-control">
                  <label class="toggle">
                    <input 
                      v-model="notificationSettings.roleUpdates" 
                      type="checkbox"
                      @change="saveNotificationSettings"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 隐私设置 -->
          <div v-if="activeTab === 'privacy'" class="settings-section">
            <h2 class="section-title">隐私设置</h2>
            
            <div class="setting-group">
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">公开个人资料</h3>
                  <p class="setting-desc">允许其他用户查看你的个人资料</p>
                </div>
                <div class="setting-control">
                  <label class="toggle">
                    <input 
                      v-model="privacySettings.publicProfile" 
                      type="checkbox"
                      @change="savePrivacySettings"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">显示在线状态</h3>
                  <p class="setting-desc">让其他用户知道你是否在线</p>
                </div>
                <div class="setting-control">
                  <label class="toggle">
                    <input 
                      v-model="privacySettings.showOnlineStatus" 
                      type="checkbox"
                      @change="savePrivacySettings"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">数据收集</h3>
                  <p class="setting-desc">允许收集使用数据以改善服务</p>
                </div>
                <div class="setting-control">
                  <label class="toggle">
                    <input 
                      v-model="privacySettings.dataCollection" 
                      type="checkbox"
                      @change="savePrivacySettings"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 语音设置 -->
          <div v-if="activeTab === 'voice'" class="settings-section">
            <h2 class="section-title">语音设置</h2>
            
            <div class="setting-group">
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">自动播放语音</h3>
                  <p class="setting-desc">收到AI回复时自动播放语音</p>
                </div>
                <div class="setting-control">
                  <label class="toggle">
                    <input 
                      v-model="voiceSettings.autoPlay" 
                      type="checkbox"
                      @change="saveVoiceSettings"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">语音音量</h3>
                  <p class="setting-desc">调整语音播放的音量</p>
                </div>
                <div class="setting-control">
                  <input 
                    v-model="voiceSettings.volume" 
                    type="range" 
                    min="0" 
                    max="100" 
                    class="volume-slider"
                    @change="saveVoiceSettings"
                  />
                  <span class="volume-value">{{ voiceSettings.volume }}%</span>
                </div>
              </div>
              
              <div class="setting-item">
                <div class="setting-info">
                  <h3 class="setting-label">语音速度</h3>
                  <p class="setting-desc">调整语音播放的速度</p>
                </div>
                <div class="setting-control">
                  <select 
                    v-model="voiceSettings.speed" 
                    class="setting-select"
                    @change="saveVoiceSettings"
                  >
                    <option value="0.5">慢速 (0.5x)</option>
                    <option value="0.75">较慢 (0.75x)</option>
                    <option value="1">正常 (1x)</option>
                    <option value="1.25">较快 (1.25x)</option>
                    <option value="1.5">快速 (1.5x)</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 关于 -->
          <div v-if="activeTab === 'about'" class="settings-section">
            <h2 class="section-title">关于</h2>
            
            <div class="about-content">
              <div class="app-info">
                <div class="app-logo">🤖</div>
                <h3>AI角色扮演平台</h3>
                <p class="app-version">版本 1.0.0</p>
                <p class="app-desc">
                  一个让用户与各种AI角色进行对话的平台，支持文本和语音交互。
                </p>
              </div>
              
              <div class="links-section">
                <h4>相关链接</h4>
                <div class="links-grid">
                  <a href="#" class="link-item">用户协议</a>
                  <a href="#" class="link-item">隐私政策</a>
                  <a href="#" class="link-item">帮助中心</a>
                  <a href="#" class="link-item">意见反馈</a>
                </div>
              </div>
              
              <div class="danger-zone">
                <h4>危险操作</h4>
                <button class="btn btn-danger" @click="deleteAccount">
                  删除账户
                </button>
                <p class="danger-warning">
                  删除账户将永久删除所有数据，此操作不可撤销。
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 修改密码模态框 -->
    <div v-if="showPasswordModal" class="modal-overlay" @click="showPasswordModal = false">
      <div class="modal-content" @click.stop>
        <h2>修改密码</h2>
        <form @submit.prevent="changePassword">
          <div class="form-group">
            <label>当前密码</label>
            <input v-model="passwordForm.currentPassword" type="password" required />
          </div>
          <div class="form-group">
            <label>新密码</label>
            <input v-model="passwordForm.newPassword" type="password" required />
          </div>
          <div class="form-group">
            <label>确认新密码</label>
            <input v-model="passwordForm.confirmPassword" type="password" required />
          </div>
          <div class="form-actions">
            <button type="button" @click="showPasswordModal = false">取消</button>
            <button type="submit">修改密码</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeTab = ref('account')
const showPasswordModal = ref(false)

const tabs = [
  { id: 'account', name: '账户', icon: '👤' },
  { id: 'notifications', name: '通知', icon: '🔔' },
  { id: 'privacy', name: '隐私', icon: '🔒' },
  { id: 'voice', name: '语音', icon: '🎤' },
  { id: 'about', name: '关于', icon: 'ℹ️' }
]

const accountSettings = ref({
  username: '',
  email: ''
})

const notificationSettings = ref({
  email: true,
  push: true,
  roleUpdates: true
})

const privacySettings = ref({
  publicProfile: true,
  showOnlineStatus: true,
  dataCollection: false
})

const voiceSettings = ref({
  autoPlay: true,
  volume: 80,
  speed: 1
})

const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const loadSettings = () => {
  try {
    const user = JSON.parse(localStorage.getItem('auth_user') || '{}')
    accountSettings.value = {
      username: user.username || '',
      email: user.email || ''
    }
    
    // 从localStorage加载其他设置
    const savedNotifications = localStorage.getItem('notificationSettings')
    if (savedNotifications) {
      notificationSettings.value = JSON.parse(savedNotifications)
    }
    
    const savedPrivacy = localStorage.getItem('privacySettings')
    if (savedPrivacy) {
      privacySettings.value = JSON.parse(savedPrivacy)
    }
    
    const savedVoice = localStorage.getItem('voiceSettings')
    if (savedVoice) {
      voiceSettings.value = JSON.parse(savedVoice)
    }
  } catch (e) {
    console.error('加载设置失败', e)
  }
}

const saveAccountSettings = async () => {
  try {
    const token = localStorage.getItem('auth_token')
    const res = await fetch('/api/users/profile', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(accountSettings.value)
    })
    
    const data = await res.json()
    if (data.code === 0) {
      // 更新本地存储的用户信息
      const user = JSON.parse(localStorage.getItem('auth_user') || '{}')
      user.username = accountSettings.value.username
      user.email = accountSettings.value.email
      localStorage.setItem('auth_user', JSON.stringify(user))
    }
  } catch (e) {
    console.error('保存账户设置失败', e)
  }
}

const saveNotificationSettings = () => {
  localStorage.setItem('notificationSettings', JSON.stringify(notificationSettings.value))
}

const savePrivacySettings = () => {
  localStorage.setItem('privacySettings', JSON.stringify(privacySettings.value))
}

const saveVoiceSettings = () => {
  localStorage.setItem('voiceSettings', JSON.stringify(voiceSettings.value))
}

const changePassword = async () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    alert('两次输入的密码不一致')
    return
  }
  
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    const res = await fetch('/api/users/change-password', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        currentPassword: passwordForm.value.currentPassword,
        newPassword: passwordForm.value.newPassword
      })
    })
    
    const data = await res.json()
    if (data.code === 0) {
      alert('密码修改成功')
      showPasswordModal.value = false
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    } else {
      alert('密码修改失败：' + data.message)
    }
  } catch (e) {
    console.error('修改密码失败', e)
    alert('修改密码失败，请重试')
  }
}

const deleteAccount = () => {
  if (!confirm('确定要删除账户吗？此操作不可撤销，所有数据将被永久删除。')) {
    return
  }
  
  if (!confirm('请再次确认：你真的要删除账户吗？')) {
    return
  }
  
  // TODO: 实现删除账户逻辑
  alert('删除账户功能暂未实现')
}

onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.settings-page {
  height: 100%;
  background: #f8fafc;
  padding: 40px 0;
  overflow-y: auto;
}

.container {
  width: 100%;
  padding: 0 32px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 1.125rem;
  color: #6b7280;
}

.settings-container {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  overflow: hidden;
}

.settings-nav {
  background: #f9fafb;
  padding: 24px 0;
  border-right: 1px solid #e5e7eb;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 12px 24px;
  background: none;
  border: none;
  text-align: left;
  cursor: pointer;
  transition: all 0.2s;
  color: #6b7280;
  font-weight: 500;
}

.nav-item:hover {
  background: #f3f4f6;
  color: #374151;
}

.nav-item.active {
  background: #667eea;
  color: white;
}

.nav-icon {
  font-size: 18px;
}

.settings-content {
  padding: 32px;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24px;
}

.setting-group {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;
  border-bottom: 1px solid #e5e7eb;
}

.setting-info {
  flex: 1;
}

.setting-label {
  font-size: 1rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.setting-desc {
  font-size: 14px;
  color: #6b7280;
}

.setting-control {
  display: flex;
  align-items: center;
  gap: 12px;
}

.setting-input,
.setting-select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  min-width: 200px;
}

.toggle {
  position: relative;
  display: inline-block;
  width: 48px;
  height: 24px;
}

.toggle input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 24px;
}

.toggle-slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

.toggle input:checked + .toggle-slider {
  background-color: #667eea;
}

.toggle input:checked + .toggle-slider:before {
  transform: translateX(24px);
}

.volume-slider {
  width: 120px;
}

.volume-value {
  font-size: 14px;
  color: #6b7280;
  min-width: 40px;
}

.about-content {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.app-info {
  text-align: center;
  padding: 32px;
  background: #f9fafb;
  border-radius: 12px;
}

.app-logo {
  font-size: 4rem;
  margin-bottom: 16px;
}

.app-info h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.app-version {
  color: #6b7280;
  margin-bottom: 16px;
}

.app-desc {
  color: #6b7280;
  line-height: 1.6;
}

.links-section h4,
.danger-zone h4 {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 16px;
}

.links-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
}

.link-item {
  padding: 12px 16px;
  background: #f3f4f6;
  color: #374151;
  text-decoration: none;
  border-radius: 8px;
  text-align: center;
  transition: all 0.2s;
}

.link-item:hover {
  background: #e5e7eb;
}

.danger-zone {
  padding: 24px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 12px;
}

.btn-danger {
  background: #dc2626;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-danger:hover {
  background: #b91c1c;
}

.danger-warning {
  color: #dc2626;
  font-size: 14px;
  margin-top: 8px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 32px;
  width: 90%;
}

.modal-content h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.form-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.form-actions button[type="button"] {
  background: #f3f4f6;
  color: #374151;
}

.form-actions button[type="submit"] {
  background: #667eea;
  color: white;
}

@media (max-width: 768px) {
  .settings-container {
    grid-template-columns: 1fr;
  }
  
  .settings-nav {
    display: flex;
    overflow-x: auto;
    padding: 16px;
  }
  
  .nav-item {
    white-space: nowrap;
    min-width: 120px;
  }
  
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .setting-control {
    width: 100%;
    justify-content: flex-start;
  }
  
  .setting-input,
  .setting-select {
    min-width: auto;
    width: 100%;
  }
}
</style>
